#!/bin/bash
yum -y install vim net-tools bridge-utils qemu-kvm libvirt virt-install libguestfs libguestfs-tools curl

# 启动libvirt并设置开机自启动
systemctl start libvirtd
systemctl enable libvirtd
# 关闭NetworkManager服务
chkconfig NetworkManager off
service NetworkManager stop

function upgrade_kernel() {
  # upgrade kernel
  kernel_package_name=$(curl -s https://elrepo.org/linux/kernel/el7/x86_64/RPMS/ | grep kernel-lt | awk -F"href=" 'NR==1{ print $2 }' | awk -F'"' '{ print $2 }')
  kernel_devel_name=$(curl -s https://elrepo.org/linux/kernel/el7/x86_64/RPMS/ | grep kernel-lt-devel | awk -F"href=" 'NR==1{ print $2 }' | awk -F'"' '{ print $2 }')
  
  yum -y update --exclude=kernel*
  if [ ! -f $kernel_package_name ];then
    curl -o $kernel_package_name https://elrepo.org/linux/kernel/el7/x86_64/RPMS/$kernel_package_name
  fi
  if [ ! -f $kernel_devel_name ];then
    curl -o $kernel_devel_name https://elrepo.org/linux/kernel/el7/x86_64/RPMS/$kernel_devel_name
  fi

  yum -y localinstall kernel-lt-*
  grub2-set-default 0 && grub2-mkconfig -o /etc/grub2.cfg
  grubby --args="user_namespace.enable=1" --update-kernel="$(grubby --default-kernel)"
  modprobe -a kvm
}

upgrade_kernel
# 新建存放镜像目录
mkdir -p /kvm/{vdisks,isos,modify}
reboot
# virsh iface-bridge enp0s3 br0
# 安装镜像
virt-install --name=liuwei --memory=512,maxmemory=1024 --vcpus=1,maxvcpus=2 --os-type=linux \
#--os-variant=rhel7 \
#--location=/kvm/isos/CentOS-7-x86_64-Minimal-1908.iso \
#--disk path=/kvm/vdisks/liuwei.img,size=10  \
#--network bridge=br0  \
#--graphics=none \
#--console=pty,target_type=serial \
#--extra-args="console=tty0 console=ttyS0"

#停止主机：
#virsh destroy liuwei
#删除主机定义：
#virsh undefine liuwei
#删除KVM虚拟机文件： 
#rm -f /kvm/vdisks/liuwei.img

